import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:yysk_app/env/env.dart';
import 'package:yysk_app/model/common_model/my_fans_model.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/empty_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:oktoast/oktoast.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:screenshot/screenshot.dart';

class InvitedPage extends StatefulWidget {
  static const path = '/InvitedPage';
  const InvitedPage({super.key});

  @override
  State<InvitedPage> createState() => _InvitedPage();
}

class _InvitedPage extends State<InvitedPage> {
  // 将 list 提升为类的成员变量
  List<MyFansItem> lists = [];
  GlobalController globalController = Get.find();
  final ScrollController scrollController = ScrollController();
  ScreenshotController screenshotController = ScreenshotController();
  final Rx<Uint8List?> screenImg = Rx<Uint8List?>(null);
  final env = Env.envConfig;
  int pageNum = 1;
  late int total = 0;
  @override
  void initState() {
    super.initState();

    _getList();

    Future.delayed(const Duration(milliseconds: 1500), () {
      screenshotController.capture().then((img) {
        screenImg.value = img!;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    final userInfo = globalController.user.value;
    return Scaffold(
      extendBodyBehindAppBar: true, // 内容延伸到AppBar后面
      body: MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: Container(
          padding: EdgeInsets.fromLTRB(0.px, 0, 0.px, 0.px),
          child: ListView(
            children: [
              Stack(
                children: [
                  Screenshot(
                    controller: screenshotController,
                    child: Container(
                      width: MediaQuery.of(context).size.width,
                      height: MediaQuery.of(context).size.height,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage(
                            'static/images/invite/background_pic.png',
                          ),
                          fit: BoxFit.fitWidth,
                        ),
                      ),
                      child: Stack(
                        children: [
                          Positioned(
                            left: 39.px,
                            bottom: 71.px,
                            child: QrImageView(
                              data:
                                  '${env.envInvitedBaseUrl}?inviteCode=${userInfo?.inviteCode}&head=${Uri.encodeComponent('${userInfo?.avatarImg}')}',
                              version: QrVersions.auto,
                              size: 86.px,
                              gapless: false,
                            ),
                          ),
                          Positioned(
                            left: 24.px,
                            bottom: 56.px,
                            child: ImageAssetWidget(
                              imageUrl: 'static/images/invite/invite_box.png',
                              width: 115.px,
                              height: 114.px,
                              fit: BoxFit.fitWidth,
                            ),
                          ),

                          Positioned(
                            left: 161.px,
                            bottom: 103.px,
                            child: Text(
                              '邀请码：${userInfo?.inviteCode}',
                              style: TextStyle(
                                fontSize: 20.px,
                                fontFamily: 'CustomFont',
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Positioned.fill(
                    child: Container(
                      color: AppColors.backgroundColor,
                      child: ImageAssetWidget(
                        imageUrl: 'static/images/invite/bg.png',
                        width: 375.px,
                        height: context.height,
                        fit: BoxFit.fitWidth,
                        alignment: Alignment.topCenter,
                      ),
                    ),
                  ),
                  Column(
                    children: [
                      SizedBox(height: top),
                      CustomAppBar2(title: '', context: context),
                      ImageAssetWidget(
                        imageUrl: 'static/images/invite/title.png',
                        width: 375.px,
                        height: 204.px,
                      ),

                      SizedBox(height: 14.px),
                      Center(
                        child: Container(
                          height: 241.px,
                          width: 238.px,
                          decoration: BoxDecoration(
                            color: AppColors.backgroundColor,
                            borderRadius: BorderRadius.circular(12.px),
                          ),
                          child: QrImageView(
                            data:
                                '${env.envInvitedBaseUrl}?inviteCode=${userInfo?.inviteCode}&head=${Uri.encodeComponent('${userInfo?.avatarImg}')}',
                            version: QrVersions.auto,
                            size: 258.px,
                            gapless: false,
                            padding: EdgeInsets.all(20.px),
                          ),
                        ),
                      ),
                      SizedBox(height: 25.px),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(
                            '我的邀请码：${userInfo?.inviteCode}',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              color: AppColors.fontColorBlack,
                              fontSize: 16.px,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              Clipboard.setData(
                                ClipboardData(
                                  text:
                                      '${userInfo?.inviteCode}', //userInfo.avatarImg
                                ),
                              );
                              showToast('复制成功');
                            },
                            child: ImageAssetWidget(
                              imageUrl: 'static/images/invite/copy2.png',
                              width: 22.px,
                              height: 22.px,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 36.px),
                      Padding(
                        padding: EdgeInsets.only(left: 19.px, right: 19.px),

                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            GestureDetector(
                              onTap: () {
                                _saveScreenshot(imgBytes: screenImg.value);
                              },
                              child: ImageAssetWidget(
                                imageUrl:
                                    'static/images/invite/invited_left.png',
                                width: 156.px,
                                height: 55.px,
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                Clipboard.setData(
                                  ClipboardData(
                                    text:
                                        '${env.envInvitedBaseUrl}?inviteCode=${userInfo?.inviteCode}&head=${Uri.encodeComponent('${userInfo?.avatarImg}')}' ??
                                        '暂无数据', //userInfo.avatarImg
                                  ),
                                );
                                showToast('复制成功');
                              },
                              child: ImageAssetWidget(
                                imageUrl:
                                    'static/images/invite/invited_right.png',
                                width: 156.px,
                                height: 55.px,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 18.px),
                      Stack(
                        children: [
                          ImageAssetWidget(
                            imageUrl: 'static/images/invite/title2.png',
                            width: 375.px,
                            height: 46.px,
                          ),
                          SizedBox(
                            width: 375.px,
                            height: 46.px,
                            child: Center(
                              child: Text(
                                '我的社区$total人',
                                style: TextStyle(
                                  color: AppColors.fontColorBlack,
                                  fontFamily: 'CustomFont',
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 52.px),
                      Center(
                        child: ImageAssetWidget(
                          imageUrl: 'static/images/invite/shequ.png',
                          width: 192.px,
                          height: 22.px,
                        ),
                      ),
                      SizedBox(height: 22.px),
                      Padding(
                        padding: EdgeInsets.only(left: 21.px, right: 12.px),
                        child: Column(
                          children: [
                            Container(
                              width: 341.px,
                              height: 38.px,
                              color: AppColors.fontColorgrey200,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    width: 189.px,
                                    height: 38.px,
                                    padding: EdgeInsets.only(left: 20.px),
                                    child: Center(
                                      child: SizedBox(
                                        width: 189.px,
                                        child: Text(
                                          '账号',
                                          style: TextStyle(
                                            color: AppColors.fontColorBlack,
                                            fontFamily: 'CustomFont',
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                  Center(
                                    child: Container(
                                      width: 150.px,
                                      padding: EdgeInsets.only(left: 20.px),
                                      height: 38.px,
                                      child: Center(
                                        child: SizedBox(
                                          width: 189.px,
                                          child: Text(
                                            '最高身份',
                                            style: TextStyle(
                                              color: AppColors.fontColorBlack,
                                              fontFamily: 'CustomFont',
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            //    RefreshAndScrollWidget(
                            //   onRefresh: _handleRefresh,
                            //   scrollController: scrollController,
                            //   itemBuilder: (item, index) =>
                            //       _item(context: context, item: item,index: index),
                            //   itemCount: list.length,
                            //   items: list,
                            // ),
                            ...lists.asMap().entries.map((entry) {
                              final index = entry.key;
                              final e = entry.value;
                              return _item(
                                context: context,
                                item: e,
                                index: index,
                              );
                            }),
                            if (lists.isEmpty) EmptyWidget(),
                            SizedBox(height: 40.px),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  _item({
    required BuildContext context,
    required MyFansItem item,
    dynamic index,
  }) {
    return Container(
      color:
          index % 2 == 0
              ? AppColors.backgroundColorGreyF2
              : AppColors.fontColorgrey200,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            width: 189.px,
            height: 74.px,
            padding: EdgeInsets.only(left: 9.px),
            child: Center(
              child: SizedBox(
                width: 189.px,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    LazyImage(
                      imageUrl: "${item.avatarImg}",
                      width: 33.px,
                      height: 33.px,
                      borderRadius: 100.px,
                    ),
                    SizedBox(width: 9.px),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "${item.nickName}",
                            style: TextStyle(
                              color: AppColors.fontColorBlack,
                              fontFamily: 'CustomFont',
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          Text(
                            "${item.createTime}",
                            style: TextStyle(
                              color: AppColors.fontColorGrey,
                              fontSize: 10.px,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Container(
            width: 1.px,
            height: 74.px,
            color: AppColors.backgroundColorGrey,
          ),
          Center(
            child: Container(
              width: 150.px,
              height: 74.px,
              padding: EdgeInsets.only(left: 20.px),
              child: Center(
                child: SizedBox(
                  width: 189.px,
                  child: Text(
                    '${item.levelName}',
                    style: TextStyle(
                      color: AppColors.fontColorBlack,
                      fontSize: 10.px,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _getList({loadMore = false}) async {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    await http.netFetch<MyFansModel>(
      CommonApi.fansPage,
      method: Method.post,
      params: {'pageNum': pageNum, 'pageSize': 1000},
      success: (result) {
        List<MyFansItem> items = result.data?.list ?? [];
        if (loadMore && items.isEmpty) {
          pageNum--;
        }
        if (!loadMore) {
          lists.clear();
        }
        setState(() {
          lists.addAll(items);
          total = result.data!.total!;
        });
      },
    );
  }

  Future<void> _saveScreenshot({Uint8List? imgBytes}) async {
    // showToast( '点击');
    try {
      // 请求权限
      final PermissionState permission =
          await PhotoManager.requestPermissionExtend();

      if (!permission.isAuth) {
        showToast('保存失败：需要相册访问权限');
        return;
      }
      if (imgBytes == null) {
        showToast('制图中,请稍后点击保存');
        return;
      }
      // 保存到相册
      final AssetEntity? asset = await PhotoManager.editor.saveImage(
        imgBytes,
        filename:
            'Flutter_Screenshot_${DateTime.now().millisecondsSinceEpoch}.png',
      );

      if (asset != null) {
        showToast('保存成功');
      } else {
        // throw Exception('保存失败: ${result['errorMessage']}');
      }
    } catch (e) {
      showToast('保存失败');
    }
  }

  _handleRefresh() {
    _getList();
  }
}
